package com.hlhj.carview.aty

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Build
import android.os.Handler
import android.os.Message
import android.support.annotation.RequiresApi
import android.support.v7.widget.RecyclerView
import android.view.View
import com.bumptech.glide.Glide
import com.example.mymvp.log
import com.google.gson.Gson
import com.hlhj.carview.BaseAty
import com.hlhj.carview.Constant
import com.hlhj.carview.Iview.MainView
import com.hlhj.carview.Iview.MyAdvView
import com.hlhj.carview.R
import com.hlhj.carview.adapter.AdvPagerListAdp
import com.hlhj.carview.bean.AdvListBean
import com.hlhj.carview.bean.MainPagerBean
import com.hlhj.carview.bean.MainPagerDataBean
import com.hlhj.carview.bean.WeatherBean
import com.hlhj.carview.customView.SlideLockView
import com.hlhj.carview.http.Apis
import com.hlhj.carview.http.CustomAction
import com.hlhj.carview.http.Urls
import com.hlhj.carview.presenter.MainPresenter
import com.hlhj.carview.presenter.MyAdvPresenter
import com.hlhj.carview.utils.GlideUtil
import com.hlhj.carview.utils.SPHelper
import com.liaoinstan.springview.utils.DensityUtil
import com.lzy.okgo.model.Response
import com.ramotion.cardslider.CardSliderLayoutManager
import com.ramotion.cardslider.CardSnapHelper
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.tbruyelle.rxpermissions.RxPermissions
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : BaseAty<MainView,MainPresenter>(), MainView, MyAdvView {
    private var advPresenter:MyAdvPresenter?=null
    private val datas=ArrayList<MainPagerDataBean>()
    private var pagerlistAdp:AdvPagerListAdp?=null

    companion object {
        var manager:CardSliderLayoutManager?=null
        var topPosition=0;
        var isVisi=true
    }

    override fun setWeather(weatherBean: WeatherBean) {
/*        val bean = weatherBean.data[0]
        tvWeather.text="${bean.tem1}  ${bean.wea}"*/


    }

    override fun getWeather() {
        Apis?.getWeather(Constant.city!!)
                ?.subscribe{
                    data->
                    try {
                        val bean = Gson().fromJson(data.body(), WeatherBean::class.java)
                        val be = bean.result?.HeWeather5?.get(0)?.now!!
                        be?.let {
                            tvWeather.text="${it.tmp} ${it.cond?.txt}"
                        }
                    }catch (e:java.lang.Exception){

                    }

                }
    }

    override fun initView() {
        pagerlistAdp= AdvPagerListAdp(datas)
        pagerList.adapter=pagerlistAdp

        userName.text="测试员"
        Glide.with(this).load(SPHelper.getHead(this)).apply(GlideUtil.loadHeadOption()).into(btSelf)
        pagerList.visibility=View.VISIBLE
        pagerList.rotation=180f

        manager = CardSliderLayoutManager(DensityUtil.dip2px(this@MainActivity,80f),
                DensityUtil.dip2px(this@MainActivity,320f),
                35f)
        pagerList.layoutManager=manager
        CardSnapHelper().attachToRecyclerView(pagerList)
        pagerList.scrollToPosition(500)



        Apis.getMainPagers()
                ?.let {
                    it.subscribe {
                        val bean=it.body()

                        datas.addAll(bean.data)
                        topPosition=datas.size-1
                        pagerList.scrollToPosition(datas.size-1)
                        pagerlistAdp?.notifyDataSetChanged()
                    }
                }

        mTextView.mContent="把握新时期用工方式、劳动关系等发生的新情况新变化,关注货运信息平台为主体的新生产方式、新企业组织形式下货车司机的权益维护情况,围绕平台企业工会工作、货车司机问题诉求、行业发展状况开展调查研究"
    }

    override fun setAdvList(advListBean: AdvListBean) {

    }

    override fun logicStart() {
        val b = RxPermissions.getInstance(this).isGranted(Manifest.permission.ACCESS_FINE_LOCATION)
                &&RxPermissions.getInstance(this).isGranted(Manifest.permission.ACCESS_COARSE_LOCATION)
                &&RxPermissions.getInstance(this).isGranted(Manifest.permission.CALL_PHONE)
        if (!b){
            RxPermissions.getInstance(this).request(Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.CALL_PHONE)
                    .subscribe {
                        b->
                        if(b){
                            presenter?.initLocation(this@MainActivity)
                        }else{

                        }
                    }
        }else{
            presenter?.initLocation(this@MainActivity)
        }

    }

    override fun onPause() {
        super.onPause()
        isVisi=false
        GSYVideoManager.onPause()
    }
    var tag=false
    override fun onBackPressed() {
        if (!tag){
            tag=true
            Thread(Runnable {
                Thread.sleep(2000)
                tag=false
            })
        }else{
            super.onBackPressed()
        }

    }
    override fun onResume() {
        super.onResume()
        isVisi=true
        GSYVideoManager.onResume()
    }

    @SuppressLint("MissingSuperCall")
    override fun onDestroy() {
        super.onDestroy()
        GSYVideoManager.releaseAllVideos()
    }
    private val notifyHandler= @SuppressLint("HandlerLeak")
    object :Handler(){
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            pagerlistAdp?.notifyDataSetChanged()
        }
    }
    @RequiresApi(Build.VERSION_CODES.M)
    override fun setListener() {
        f.setOnClickListener {
            val intent = Intent(this, ItemAskAty::class.java)
            startActivity(intent)
        }
        pagerList?.addOnScrollListener(object :RecyclerView.OnScrollListener(){
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)

                if (newState==0){
                    try {
                        notifyHandler?.removeMessages(1)
                        val i = manager?.activeCardPosition
                        topPosition=i!!
                        notifyHandler?.sendEmptyMessageDelayed(1,500)
                    }catch (e:Exception){

                    }

                }
            }
        })
        btNews.setOnClickListener {
            val intent = Intent(this, ArticalAty::class.java)
            startActivityForResult(intent,REFRESH)
        }
        btSelf.setOnClickListener {
            val intent = Intent(this, UserAty::class.java)

            startActivityForResult(intent,REFRESH)
        }
        lockView.setmLockListener (object :SlideLockView.OnLockListener{
            override fun onOpenLockSuccess() {
                val i = Intent(this@MainActivity, NavAty::class.java)
                i.putExtra("head",intent.getStringExtra("head"))
                startActivityForResult(i,REFRESH)
            }
        })
        pagerlistAdp?.setOnItemClickListener { adapter, view, position ->
            val intent = Intent(this, ItemAskAty::class.java)
            val name=datas[position].name
            if (name.contains("水")){
                intent.putExtra("name","水果")
            }
            if (name.contains("贵")){
                intent.putExtra("name","贵重品")
            }
            if (name.contains("衣")){
                intent.putExtra("name","衣物")
            }
            if (name.contains("碎")){
                intent.putExtra("name","易碎品")
            }
            startActivity(intent)
        }
        lockView.startLoop()
    }

    private val REFRESH=11

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode!=-1)return
        if (requestCode==REFRESH){
            Glide.with(this).load(SPHelper.getHead(this)).into(btSelf)
        }
    }
    override fun bindView(): MainView {
        return this
    }

    override fun createPresenter(): MainPresenter {
        presenter?.c=this@MainActivity
        advPresenter= MyAdvPresenter()
        advPresenter?.let {
            it.createModule()
            it.bindView(this@MainActivity)
        }
        return MainPresenter()
    }
    override fun getContentID(): Int {
        return R.layout.activity_main
    }
}
